﻿using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Msung.Core.Caching;
using Msung.Core;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;
using Quartz.Util;

namespace JobService.Jobs
{
    public class ExecuteErrorSqlServiceJob : IJob
    {
        private readonly ILogger logger;
        private readonly IServiceProvider serviceProvider;
        public ExecuteErrorSqlServiceJob(
            IServiceProvider serviceProvider,
            ILogger<ExecuteErrorSqlServiceJob> logger)
        {
            this.logger = logger;
            this.serviceProvider = serviceProvider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                using (var scope = serviceProvider.CreateScope())
                {
                    var _redisRepository = scope.ServiceProvider.GetRequiredService<IRedisOperationRepository>();
                    var listCount = await _redisRepository.ListLengthAsync("SqlErrorList");
                    if (listCount == 0) return;
                    var sql = await _redisRepository.ListRightPopAsync("SqlErrorList");

                    var _freeSqlCloud = scope.ServiceProvider.GetRequiredService<FreeSqlCloud<string>>();
                    var _freesql = _freeSqlCloud.Change("TRACER");
                    try
                    {
                        Task.Factory.StartNew(() =>
                        {
                            _freesql.Ado.ExecuteNonQuery(sql);
                        });
                    }
                    catch (Exception ex)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            RunErrorSql(sql);
                        });
                    }

                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
            }
        }

        object errolock = new object();
        private void RunErrorSql(string sql)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var _freeSqlCloud = scope.ServiceProvider.GetRequiredService<FreeSqlCloud<string>>();
                var _freesql = _freeSqlCloud.Change("TRACER");
                Task.Factory.StartNew(() =>
                {
                    sql = sql.Replace("BEGIN", "");
                    sql = sql.Replace("END", "");
                    string[] sqls = sql.Split(';');
                    foreach (var item in sqls)
                    {
                        if (item.Trim().IsNullOrWhiteSpace()) continue;
                        try
                        {
                            _freesql.Ado.ExecuteNonQuery(item);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError("定时执行Erro SQL语句服务异常:" + ex.Message + "\r\n" + item, ex.InnerException + "\r\n" + item);
                        }
                    }
                });
            }
        }
    }
}
